package master;

import java.util.ArrayList;
import java.util.List;

/**路径总和II
 *
 * @author chenyw
 * @date 2022/8/6 13:03
 */
public class M113pathSum {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return res;
        }
        dfs(root, targetSum, 0, new ArrayList<Integer>());
        return res;
    }

    private void dfs(TreeNode root, int targetSum, int sum, ArrayList<Integer> list) {
        if (root == null) {
            return;
        }
        sum += root.val;
        list.add(root.val);
//        if (root.left ==null && root.right == null) {
//            if (sum == targetSum) {
//                res.add(new ArrayList<>(list));
//                return;
//            }
//            return;
//        }
        dfs(root.left, targetSum, sum, list);
        dfs(root.right, targetSum, sum, list);
        if (root.right == null && root.left == null) {
            if (sum ==targetSum) {
                res.add(new ArrayList<>(list));
            }
        }
        sum -= root.val;
        list.remove(list.size() - 1);
    }
}
